Skip to main content

Основы Java и Scala

03. Библиотека коллекций в Java

Материалы

Презентация: JavaCollections.pptx

Задание

Проект с заданием: lession03.zip

Юнит тестирование

Документация​

JUnit4:  https://junit.org/junit4/

JUnit4 включает в себя библиотеку Hamcrest.

Как добавить в проект  в Idea​

  1. В корне проекта создать директорию test (Alt+Insert → Directory)
  2. Пометить директорию test как "Test Resource Root" (правой кнопкой мыши на директории test → Mark Directory as → Test Resource Root)
  3. На классе или методе, который необходимо протестировать Ctrl+Shift+T → Create New Test. В диалоге выбрать Testing Library → JUnit4 и нажать кнопку Fix чтобы добавить библиотеку JUnit в classpath.

Пример​

Протестируем метод convert клаcса CurrencyExchangeRate:

CurrencyExchangeRateTest Развернуть исходный код

package org.mai.dep810.cer;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.Currency;

import static org.junit.Assert.*;


public class CurrencyExchangeRateTest {
@Before
public void setUp() throws Exception {
}

@After
public void tearDown() throws Exception {
}

@Test(expected = IncorrectExchangeRateException.class)
public void convertTest() throws Exception {
Currency usd = Currency.getInstance("USD");
Currency gbp = Currency.getInstance("GBP");
Currency eur = Currency.getInstance("EUR");

Money hundredDollars = new Money(usd, new BigDecimal(100));
Money hundredEurs = new Money(eur, new BigDecimal(100));

CurrencyExchangeRate usdToPound = new CurrencyExchangeRate(new BigDecimal(0.75), usd, gbp);

Money usdConvertedToPounds = usdToPound.convert(hundredDollars);

assertEquals(usdConvertedToPounds.getCurrency(), gbp);
assertEquals(usdConvertedToPounds.getAmount(), new BigDecimal(75).setScale(2));

Money eurCoverted = usdToPound.convert(hundredEurs);
}

}

Реализация класса CurrencyExchangeRate

CurrencyExchangeRate Развернуть исходный код

package org.mai.dep810.cer;

import java.math.BigDecimal;
import java.util.Currency;

public class CurrencyExchangeRate {

BigDecimal rate;
Currency from;
Currency to;

public CurrencyExchangeRate(BigDecimal rate, Currency from, Currency to) {
this.rate = rate;
this.from = from;
this.to = to;
}

public Money convert(Money m) {
if(m.getCurrency().equals(from)) {
return new Money(to, m.getAmount().multiply(rate));
} else {
throw new IncorrectExchangeRateException("Unable to convert currency "+m.getCurrency().getCurrencyCode() + " from "+from.getCurrencyCode());
}
}
}

Стандартная библиотека коллекций

Tutorial:  https://docs.oracle.com/javase/tutorial/collections/index.html

Альтернативные библиотеки коллекций

Apache Commons Collections​

Home page:  http://commons.apache.org/proper/commons-collections/

Google Guava​

Home page:  https://code.google.com/archive/p/google-collections/

User guide:  https://github.com/google/guava/wiki